package attendance

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/attendance"
	attendanceReq "github.com/flipped-aurora/gin-vue-admin/server/model/attendance/request"
)

type StudentService struct {
}

// CreateStudent 创建学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) CreateStudent(stu *attendance.Student) (err error) {

	err = global.GVA_DB.Create(stu).Error
	return err
}

// DeleteStudent 删除学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) DeleteStudent(ID string) (err error) {
	err = global.GVA_DB.Delete(&attendance.Student{}, "id = ?", ID).Error
	return err
}

// DeleteStudentByIds 批量删除学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) DeleteStudentByIds(IDs []string) (err error) {
	err = global.GVA_DB.Delete(&[]attendance.Student{}, "id in ?", IDs).Error
	return err
}

// UpdateStudent 更新学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) UpdateStudent(stu attendance.Student) (err error) {
	err = global.GVA_DB.Model(&attendance.Student{}).Where("id = ?", stu.ID).Updates(&stu).Error
	return err
}

// GetStudent 根据ID获取学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) GetStudent(ID string) (stu attendance.Student, err error) {
	err = global.GVA_DB.Where("id = ?", ID).First(&stu).Error
	return
}

// GetStudentInfoList 分页获取学生表记录
// Author [piexlmax](https://github.com/piexlmax)
func (stuService *StudentService) GetStudentInfoList(info attendanceReq.StudentSearch, belongTo uint) (list []attendance.Student, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&attendance.Student{})
	db = db.Where("belong_to = ?", belongTo)
	var stus []attendance.Student
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Id != "" {
		db = db.Where("id = ?", info.Id)
	}
	if info.Name != "" {
		db = db.Where("name = ?", info.Name)
	}
	if info.Class_id != "" {
		db = db.Where("class_id = ?", info.Class_id)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["id"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&stus).Error
	return stus, total, err
}
